package club.janna.netty.encode;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 编码器客户端
 */
public class EncodeClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new UserEncoder());
                        ch.pipeline().addLast(new BizHandler());
                    }
                });
        ChannelFuture future = bootstrap.connect("localhost", 8080).sync();
        System.out.println("已连接");
        future.channel().closeFuture().sync();
    }

    /**
     * 业务处理器，一定延时后，发送一个用户对象
     */
    private static class BizHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("已建立连接");
            Random random = new Random();
            ctx.executor().schedule(() -> {
                for (int i = 0; i < 5; i++) {
                    User user = new User((long)random.nextInt(1000), random.nextInt(18), "guopanbo");
                    System.out.println("发送数据 -> " + user);
                    ctx.channel().writeAndFlush(user);
                }
            }, 1, TimeUnit.SECONDS);
        }
    }

    /**
     * 用户编码器
     *
     * +------+--------+------+------+----------+
     * | HEAD | Length | ID   | Age  | Name     |
     * | 0xCA | 0x0014 | 0x01 | 0x18 | guopanbo |
     * +------+--------+------+------+----------+
     */
    private static class UserEncoder extends MessageToByteEncoder<User> {

        @Override
        protected void encode(ChannelHandlerContext ctx, User msg, ByteBuf out) throws Exception {
            byte[] bytes = msg.getName().getBytes();
            // 总的报文长度 long = 8, int = 4
            int length = bytes.length + 8 + 4;
            out.writeByte(0xCA); // 写入报文头
            out.writeShort(length); // 写入长度，占两个字节
            out.writeLong(msg.getId());
            out.writeInt(msg.getAge());
            out.writeBytes(bytes);
        }
    }
}
